package study.eggs.springcloud.gateway.support.utils;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.Map;

/**
 * 响应写入
 */
public final class WriteUtils {

    private static final String DEFAULT_CONTENT_TYPE = "application/json;charset=UTF-8";

    private WriteUtils() {
    }

    public static Mono<Void> write(ServerWebExchange exchange, HttpStatus status) {
        ServerHttpResponse response = WebUtils.getHttpResponse(exchange);
        response.setStatusCode(status);
        return response.setComplete();
    }

    public static Mono<Void> write(ServerWebExchange exchange, String body) {
        return write(exchange, body, Collections.EMPTY_MAP);
    }

    public static Mono<Void> write(ServerWebExchange exchange, String body, Map<String, String> headers) {
        return write(exchange, body, headers, DEFAULT_CONTENT_TYPE);
    }

    /**
     * 写入
     *
     * @param exchange    ServerWebExchange（交换器）
     * @param body        String（响应体）
     * @param headers     Map<String, String>（响应头部）
     * @param contentType String（内容类型）
     */
    public static Mono<Void> write(ServerWebExchange exchange, String body, Map<String, String> headers, String contentType) {
        ServerHttpResponse response = WebUtils.getHttpResponse(exchange);
        //响应码
        response.setStatusCode(HttpStatus.OK);
        //响应头
        WebUtils.addResponseHeader(exchange, "Content-Type", contentType);
        if (headers != null) {
            headers.entrySet().stream()
                    .forEach(e -> WebUtils.addResponseHeader(exchange, e.getKey(), e.getValue()));
        }
        //响应体
        byte[] bodyByte = body.getBytes();
        DataBuffer buffer = response.bufferFactory().wrap(bodyByte);
//        response.writeWith(Mono.just(buffer));
        return response.writeWith(Mono.just(buffer));
    }
}
